<template>
  <view class="deliver-page flex flex-col  h-full box-border">
    <!-- 列表 -->
    <q-previewImage v-show="isPreview" class="z-19000" ref="previewImage"
      :urls="[currentRecord.skuImageUrl || defaultImg]"></q-previewImage>
    <q-previewImage v-show="isPreviewPack" class="z-19000" ref="previewPackImage"
      :urls="[currentRecord.skuImageUrl || defaultImg]"></q-previewImage>
    <view class="flex-1 overflow-auto px-32rpx" :class="isPreview ? 'z-18000' : ''">
      <view style="margin-bottom: 48rpx;" class="common-product-list-item " v-for="(item, idx) in skuList" :key="idx">
        <view class="common-product-list-item-left">
          <!-- <up-album :urls="[item.skuImageUrl || defaultImg]"></up-album> -->
          <img style="width: 80rpx; height: 80rpx; border-radius: 8rpx; margin-right: 16rpx;"
            :src="item.skuImageUrl || defaultImg" @click="preview(item)" />
          <view>
            <view class="name maxwidth overflow-ellipsis">
              {{ item?.skuDescription || '' }}
            </view>
            <view class="sub-name">
              {{ item?.skuCode || '' }}
            </view>
          </view>
        </view>
        <view class="common-product-list-item-right min-w-200rpx">
          <view class="common-count">
            <view v-if="item?.preDeliver > 0" class="mr-14rpx icon-box">
              <up-icon class="mr-14rpx" name="minus" color="#fff" size="14" @click="minusCount(item)"></up-icon>
            </view>
            <view v-if="item?.preDeliver === '' || item?.preDeliver > 0" class="max-w-60rpx mr-14rpx border-rd-10rpx ">
              <up-input class="text-center" type="number" border="none" v-model="item.preDeliver"
                @change="change(item)">
              </up-input>
            </view>
            <view class="icon-box" :class="(item?.preDeliver) >= (item?.noDeliveryCount) ? 'gray' : ''"
              @click="addCount(item)">
              <up-icon name="plus" color="#fff" size="14"></up-icon>
            </view>
          </view>
          <view class="text-center">待发货数量{{ item?.noDeliveryCount || '' }}</view>
        </view>
      </view>
    </view>
    <!-- popup弹窗 -->
    <view class="delivery-popup-box">
      <up-popup :show="show" @close="close">
        <view class="mt-20rpx">
          <view class="common-product-list-item item-border mb-48rpx"
            v-for="(item, idx) in skuList.filter(sku => sku.preDeliver > 0 || sku.preDeliver === '')" :key="idx">
            <view class="common-product-list-item-left">
              <!-- <up-album :urls="[item.skuImageUrl || defaultImg]"></up-album> -->
              <img style="width: 80rpx; height: 80rpx; border-radius: 8rpx; margin-right: 16rpx;"
                :src="item.skuImageUrl || defaultImg" @click="previewPack(item)" />
              <view>
                <view class="name">
                  {{ item?.skuDescription || '' }}
                </view>
                <view class="sub-name">
                  好达威SKU:{{ item.skuCode || '' }}
                </view>
                <view v-if="item.supplierSkuCodes?.filter((code: string) => !!code)?.length" class="sub-name">
                  商家SKU:{{ item.supplierSkuCodes.join(',') || '' }}
                </view>
              </view>
            </view>
            <view class="common-product-list-item-right min-w-200rpx">
              <view class="common-count">
                <view v-if="item?.preDeliver > 0" class="mr-14rpx icon-box">
                  <up-icon class="mr-14rpx" name="minus" color="#fff" size="14" @click="minusCount(item)"></up-icon>
                </view>
                <view v-if="item?.preDeliver === '' || item?.preDeliver > 0"
                  class="max-w-60rpx mr-14rpx border-rd-10rpx ">
                  <up-input class="text-center" type="number" border="none" v-model="item.preDeliver"
                    @change="change(item)">
                  </up-input>
                </view>
                <view class="icon-box" :class="(item?.preDeliver) >= (item?.noDeliveryCount) ? 'gray' : ''"
                  @click="addCount(item)">
                  <up-icon name="plus" color="#fff" size="14"></up-icon>
                </view>
              </view>
            </view>
          </view>
        </view>
      </up-popup>
    </view>
    <!-- 发货弹窗 -->
    <up-modal v-if="showModal" :width="350" :show="showModal" :title="`创建包裹${packCount + 1}并发货`">
      <view class="slot-content max-h-900rpx overflow-auto">
        <up-form labelPosition="left" :labelWidth="98" :model="formData" ref="deliverFormRef" :rules="deliverRules">
          <up-form-item label="物流单号：" prop="expressNumber" :required="isRequire" ref="item1">
            <view class="wuliu-input flex relative">
              <up-input class="relative" v-model="formData.expressNumber" @blur="expressNumberBlur"></up-input>
              <view class="scan-icon" @tap.stop="() => { }">
                <up-icon name="scan" size="24" @tap="handleScan"></up-icon>
              </view>
            </view>
          </up-form-item>
          <up-form-item label="物流承运商：" prop="expressCompany" ref="item1">
            <up-input v-model="formData.expressCompany" disabled disabledColor="#ffffff" border="surround"
              placeholder="自动检测" suffixIcon="arrow-down" @tap="() => wuliuClick()"></up-input>
            <!-- <template #right>
              <up-icon name="arrow-right"></up-icon>
            </template> -->
          </up-form-item>
          <up-form-item label="发货备注：" prop="expressRemark" ref="item1">
            <up-textarea v-model="formData.expressRemark" placeholder="请输入备注" :maxlength="-1"></up-textarea>
          </up-form-item>
          <up-form-item label="备注图片：" prop="files" ref="item1">
            <div class="flex flex-wrap upload-img">
              <div :class="fileList.length >= 5 ? 'w-0' : 'w-130rpx'">
                <up-upload v-if="fileList.length < 5" :fileList="fileList" name="files" multiple :maxSize="maxSize"
                  :previewImage="false" :beforeRead="beforeRead" @afterRead="afterRead" @oversize="oversize">
                  <template #default>
                    <div class="picUpload mr-10rpx mb-10rpx">
                      <div class="flex flex-col items-center justify-center">
                        <img style="width: 50rpx; height: 50rpx;" :src="uploadImg">
                        <span class="text-20rpx text-gray">{{ `可上传${5 - fileList.length}张` }}</span>
                      </div>
                    </div>
                  </template>
                </up-upload>
              </div>
              <div v-for="picture in fileList" :key="picture.url"
                class="w-110rpx h-110rpx mr-10rpx mb-10rpx relative overflow-hidden border-rd-10rpx">
                <!-- <img style="width: 110rpx; height: 110rpx;" class="border-rd-10rpx" :src="picture.url" @click="" /> -->
                <up-album :urls="[picture.url || defaultImg]"></up-album>
                <div class="w-40rpx h-40rpx absolute -right-12rpx -top-10rpx " @click="() => deletePic(picture)">
                  <u-icon name="close-circle-fill" size="20" color="##babdc1"></u-icon>
                </div>
              </div>
            </div>
          </up-form-item>
        </up-form>
      </view>
      <template #confirmButton>
        <view class="confirmButton flex justify-center">
          <view class="btn-box mr-32rpx w-264rpx"><up-button type="primary" :plain="true" text="取消"
              @click="cancelDeliver"></up-button>
          </view>
          <view class="btn-box w-264rpx"><up-button color="#1A5FA9" type="primary" text="确认发货"
              @click="confirm"></up-button>
          </view>
        </view>
      </template>
    </up-modal>

    <!-- 底部按钮 -->
    <view class="h-148rpx w-full box-border items-center bg-#fff justify-center flex py-26rpx z-18076">
      <view class="delivery-button-left" @click.stop="open">
        <img class="w-54rpx h-54rpx mr-18rpx" src="../../static/pack.png" alt="产品图片" />
        <view>包裹{{ packCount + 1 }}（共包含{{ total }}件）</view>
      </view>
      <view class="delivery-button-right"
        :class="skuList.filter((sku) => sku.preDeliver > 0).length ? '' : 'delivery-disabled'" @click="delivery">
        发货
      </view>
    </view>
  </view>
  <!-- 底部按钮遮罩层 -->
  <view v-if="showModal" class="delivery-mask z-18100"></view>
  <!-- 物流popup弹窗 -->
  <view class="wuliu-picker" v-if="showPopup && showModal" @click.stop="showPopup = false">
    <!-- <up-picker :show="showPopup" :columns="[actions]"></up-picker> -->
    <view @click.stop="() => { }" class="custom-picker flex flex-col items-center h-380rpx"
      :class="[{ 'hide-in': showPopup }, { 'hide-out': !showPopup }]">
      <view class="custom-picker-header flex justify-between p-32rpx">
        <view class=" ml-32rpx" @tap.stop="showPopup = false">取消</view>
        <view class="color-#3c9cff mr-32rpx" @tap.stop="handlePickerCheck">确定</view>
      </view>
      <scroll-view class="custom-picker-body h-200rpx w-80vw" :scroll-y="true" :scroll-top="pickerTop"
        @scroll="(ev) => handlePickerScroll(ev)">
        <view class="pt-40px pb-40px flex flex-col">
          <view class="custom-picker-item h-40px w-full" :class="[{ 'active-picker-item': pickerIdx === index }]"
            @tap="handleClickPicker(index)" v-for="(item, index) in actions" :key="index">
            {{ item }}
            <view class="bottom-line"></view>
          </view>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { poManageQueryPoSku, poManageQueryPoPackageCount, poManageDoDeliveryPoByWx, poManageDeliveryExpressQuery } from "@/genapi/poManage";
import { kuaidQuerySelectAll } from "@/genapi/kuaid";
import defaultImg from "@/static/default.png"
import uploadImg from "@/static/picUpload.png"
import { containsSQLXSS } from "@/utils/utils";
import { chineseReg } from "@/utils/reg";
import { Url } from "url";

let uploadUrls: string[] = []
const skuList = ref([])
const preDeliverList = ref([])
const pageQuery = ref<any>({})
const previewImage = ref()
const previewPackImage = ref()
const currentRecord = ref({})
const isPreview = ref(false)
const isPreviewPack = ref(false)
onLoad((query) => {
  pageQuery.value = query
  detailId = query?.id || ''
})
let detailId = ''
const isGZStore = computed(() => pageQuery.value.isGZStore === 'true')
const isRequire = computed(() => pageQuery.value.isGZStore !== 'true')
const total = ref(0) // 产品总件数
const packCount = ref(0) // 包裹数
const show = ref(false) // 包裹弹窗
const showPopup = ref(false) //物流弹窗
const showModal = ref(false) //发货弹窗
const actions = ref([])
const pickerIdx = ref(0)
const pickerTop = ref(0)
let timer: any = null
const deliverFormRef = ref()
const fileList = ref([])
const infoFormRef = ref()
const formData = reactive({
  expressCompany: '',
  expressNumber: '',
  expressRemark: '',
})
const deliverRules = reactive({
  expressNumber: {
    type: 'string',
    required: !isGZStore.value,
    validator: (rule: any, value: string, cb: (str?: string) => void) => {
      if (!isGZStore.value && !value)
        cb('物流单号不能为空')
      else if (chineseReg.test(value))
        cb('仅允许输入英文字母、数字与符号')
      else
        cb()
    },
    trigger: ['blur'],
  },
  expressRemark: {
    type: 'string',
    validator: (rule: any, value: any, cb: (val?: any) => void) => {
      const err = containsSQLXSS(value)
      if (value && value.length > 300)
        cb('输入内容不能超出300字符')
      else if (err)
        cb('输入内容包含非法字符，请重新输入')
      else
        cb()
    },
    trigger: ['blur'],
  },
})

async function preview(item: any) {
  currentRecord.value = item
  isPreview.value = true
  await nextTick(() => {
    previewImage.value.open(item.skuImageUrl); // 传入当前选中的图片地址(小程序必须添加$nextTick，解决组件首次加载无图)
  })
};
async function previewPack(item: any) {
  currentRecord.value = item
  isPreviewPack.value = true
  await nextTick(() => {
    previewPackImage.value.open(item.skuImageUrl); // 传入当前选中的图片地址(小程序必须添加$nextTick，解决组件首次加载无图)
  })
};
watch(() => pageQuery.value.isGZStore, () => {
  deliverRules.expressNumber.required = pageQuery.value.isGZStore !== 'true'
}, { deep: true, immediate: true })

async function uploadReq(apiurl: string, apiParams?: any, name = 'files') {
  uni.showLoading({
    title: '加载中...'
  })
  if (fileList.value.length) {
    await Promise.all(fileList.value.map(async (e: any) => {
      const promise = await uploadFilePromise(apiurl, e.url, apiParams, name)
      return promise
    })).then((results) => {
      uni.hideLoading()
      const urls: string[] = []
      const errIndex: number[] = []
      const success = results.every((item: any, index) => {
        item = JSON.parse(item)
        urls.push(item.data)
        if (index !== 200) {
          errIndex.push(index)
        }
        return item.code === 200
      })
      uploadUrls = urls
      if (!success) {
        uni.showToast({
          title: apiParams ? JSON.parse(results[0]).msg : '上传失败!',
          icon: 'none'
        })
        if (!apiParams) {
          fileList.value = fileList.value.filter((item, index) => !errIndex.includes(index))
        }
      }
      if (success && apiParams) {
        fileList.value = []
        showModal.value = false
        getSkuList()
        getPackCount()
      }
    }).catch((err: any) => {
      uni.hideLoading()
      uni.showToast({
        title: '上传失败',
        icon: 'error'
      })
      console.error('上传失败:', err)
    })
  }
}
const fileType: string[] = ['jpg', 'jpeg', 'png']
const maxSize = 5 * 1024 * 1024
function oversize() {
  setTimeout(() => {
    uni.showToast({
      title: '图片大小不得超过5M!',
      icon: 'none'
    })
  }, 200);
}
async function beforeRead(file: any) {
  const files = file.map((item: any) => {
    const uuid = Date.now().toString(36) + Math.random().toString(36).slice(2, 5);
    const type: string = item.url.split('.').pop()
    item.sizePass = item.size <= maxSize
    item.typePass = fileType.includes(type.toLowerCase())
    // 是否重复
    item.samePass = fileList.value.every((img: any) => item.url.slice(-15) !== img.url.slice(-15))
    item.uuid = uuid
    return item
  })
  let typePass = files.every((item: any) => item.typePass)
  if (!typePass) {
    setTimeout(() => {
      uni.showToast({
        title: '仅支持 JPEG、JPG、PNG 格式的图片，请重新选择',
        icon: 'none'
      })
    }, 200);
  }
  let samePass = files.every((item: any) => item.samePass)
  if (!samePass) {
    setTimeout(() => {
      uni.showToast({
        title: '请勿重复上传',
        icon: 'none'
      })
    }, 200);
  }
  file = files.filter((item: any) => item.typePass && item.sizePass && item.samePass)
  if (fileList.value.length + file.length > 5) {
    setTimeout(() => {
      uni.showToast({
        title: '最多上传5张图片！',
        icon: 'none'
      })
    }, 200);
    file = file.slice(0, 5 - fileList.value.length)
  }
  fileList.value = fileList.value.concat(file)
}
async function afterRead(event: any) {
  if (!event.file?.length) return
  uploadReq('/api/poManage/deliveryFileUpload', undefined, 'file')
}
// 删除文件
async function deletePic(file: any) {
  fileList.value = fileList.value.filter((item: any) => item.uuid !== file.uuid)
}
async function expressNumberBlur() {
  const err = await infoFormRef?.value?.validateField('expressNumber')
  if (err) return
  if (formData.expressNumber) {
    const { data } = await poManageDeliveryExpressQuery({ newLogisticsNumber: formData.expressNumber })
    if (data?.code !== 200) {
      fileList.value = []
      formData.expressCompany = ''
      formData.expressRemark = ''
      return
    }
    const result = data.data || {}
    formData.expressNumber = result.expressNumber || ''
    formData.expressCompany = result.expressCompany || ''
    formData.expressRemark = result.expressRemark || ''
    if (result.expressFeedbackUrlList?.length) {
      fileList.value = result.expressFeedbackUrlList.map((item: string) => {
        const uuid = Date.now().toString(36) + Math.random().toString(36).substr(2, 5);
        return { url: item, uuid }
      })
    } else {
      fileList.value = []
    }
  }
}

function handlePickerScroll(ev) {
  let topPx = ev.detail.scrollTop
  try {
    if (timer) {
      clearTimeout(timer)
      timer = null
    }
  } catch (err) { }
  timer = setTimeout(() => {
    let tempIdx = Math.floor((topPx + 1) / 40)
    pickerIdx.value = tempIdx >= actions.value.length ? actions.value.length - 1 : tempIdx
    pickerTop.value = pickerIdx.value * 40
    try {
      if (timer) {
        clearTimeout(timer)
        timer = null
      }
    } catch (err) { }
  }, 400)
}

function handleClickPicker(idx) {
  pickerIdx.value = idx
  pickerTop.value = pickerIdx.value * 40
}

function handlePickerCheck() {
  if (!actions.value.length) return
  formData.expressCompany = actions.value[pickerIdx.value]
  nextTick(() => {
    showPopup.value = false
  })
}
function wuliuClick() {
  console.log("🚀 ~ wuliuClick ~ showPopup.value1:", showPopup.value)

  showPopup.value = true
  console.log("🚀 ~ wuliuClick ~ showPopup.value:", showPopup.value)
  // uni.hideKeyboard()
}
async function getSkuList() {
  const { data } = await poManageQueryPoSku({ poId: detailId, noCancelSku: true })
  if (data?.code !== 200) return
  else {
    const result = data.data
    skuList.value = result.map((item: any) => {
      item.preDeliver = 0
      return item
    })
  }
}
async function getPackCount() {
  const { data } = await poManageQueryPoPackageCount({ poId: detailId })
  if (data?.code !== 200) return
  else {
    const result = data.data
    packCount.value = result
  }
}
function addCount(item) {
  if (item.preDeliver < item.noDeliveryCount) {
    item.preDeliver++
    total.value++
  }
}
function minusCount(item) {
  if (item.preDeliver > 0) {
    item.preDeliver--
    total.value--
  }
}

const change = (item) => {
  if (item.preDeliver > item.noDeliveryCount) {
    uni.showToast({
      title: `发货数量不能大于待发货数量${item.noDeliveryCount}`,
      icon: 'none'
    })
    item.preDeliver = item.noDeliveryCount
    total.value = item.preDeliver
  }
  total.value = item.preDeliver
};
async function delivery() {
  if (showModal.value) return
  // 过滤发货订单
  filterDeliver()
  if (preDeliverList.value.length < 1) return
  show.value = false
  showModal.value = true
  const { data } = await kuaidQuerySelectAll()
  if (data?.code !== 200) return
  else {
    const result = data.data || []
    if (result.length) {
      actions.value = result
    }
  }
}
function cancelDeliver() {
  showModal.value = false
  deliverFormRef.value.clearValidate()
}
function uploadFilePromise(apiurl: string, fileUrl?: string, apiParams?: any, name = 'files') {
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: `${import.meta.env.VITE_BASE_API_URL}${apiurl}`,
      filePath: fileUrl || undefined,
      name,
      header: {
        Authorization: 'Bearer ' + uni.getStorageSync('token')
      },
      formData: apiParams ? { poDeliveryDto: JSON.stringify(apiParams) } : undefined,
      success: (res) => {
        resolve(res.data || true)
      },
      fail: (res) => {
        uni.showToast({
          title: res.errMsg,
          icon: 'none'
        })
        reject(res)
      }
    })
  })
}
const flag = ref(false)
async function confirm() {
  if(flag.value){
    uni.showToast({
      title: '等待执行完成',
      icon: 'none'
    })
    return
  }
  deliverFormRef.value.validate().then(async (vaild) => {
    if (vaild) {
      const deliverSkuList: any[] = []
      preDeliverList.value.length && preDeliverList.value.forEach((item) => {
        deliverSkuList.push({
          deliveryCount: item.preDeliver,
          noDeliveryCount: item.noDeliveryCount,
          poSkuId: item.id
        })
      })
      const apiParams = {
        deliverSkuList,
        expressCompany: formData.expressCompany || '',
        expressNumber: formData.expressNumber || '',
        expressRemark: formData.expressRemark || '',
        poId: detailId,
        originPhotoUrlList: uploadUrls,
      }
      flag.value = true
      const { data } = await poManageDoDeliveryPoByWx(apiParams)
      flag.value = false
      if (data?.code !== 200) return
      fileList.value = []
      formData.expressNumber = ''
      formData.expressCompany = ''
      formData.expressRemark = ''
      showModal.value = false
      uni.showToast({
        title: '发货成功',
        icon: 'none'
      })
      getSkuList()
      getPackCount()
      // const { data } = await poManageDoDeliveryPo(apiParams)
      // if (data?.code !== 200) return
      // else {
      //   uni.showToast({
      //     title: '发货成功',
      //     icon: 'success'
      //   })
      //   uni.navigateBack({
      //     delta: 1
      //   })
      // }
    }

  })

}
function filterDeliver() {
  const preDeliverArr = skuList.value.filter((sku) => sku.preDeliver > 0)
  // 先清空预发货列表
  preDeliverList.value.length = 0
  // 再放入最新预发货列表
  preDeliverList.value = preDeliverList.value.concat(preDeliverArr)
}
// 打开popup弹窗
function open() {
  if (showModal.value) return
  filterDeliver()
  if (preDeliverList.value.length < 1) {
    show.value = false
  } else {
    show.value = !show.value
  }
}
// 关闭popup弹窗
function close() {
  show.value = false;
}
function handleScan() {
  uni.scanCode({
    success: function (res) {
      formData.expressNumber = res.result
      expressNumberBlur()
    }
  });
}
onMounted(async () => {
  getSkuList()
  getPackCount()
})
onBackPress(() => {
  if (showPopup.value) {
    showPopup.value = false
    return
  } else {
    uni.navigateBack()
  }
})
</script>
<style scoped lang="scss">
.delivery-mask {
  position: fixed;
  bottom: 0;
  width: 100vw;
  height: 148rpx;
  animation: identifier 0.35s ease-in-out 0.25s forwards;
  // animation: name duration timing-function delay iteration-count direction fill-mode;

}

@keyframes identifier {
  from {
    background: rgba(0, 0, 0, 0);
  }

  to {
    background: rgba(0, 0, 0, 0.5);
  }
}

.gray {
  background: #D3D3D3;
}

.common-count {
  .icon-box {
    box-sizing: border-box;
    height: 44rpx;
    width: 44rpx;
    padding: 10rpx;
    border-radius: 10rpx;
    background: #1A5FA9;
    text-align: center;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}

.wuliu-picker {
  height: 100vh;
  width: 100vw;
  background: rgba(0, 0, 0, .5);
  position: fixed;
  top: 0;
  left: 0;
  z-index: 19001;

  .active-picker-item {
    color: #3c9cff;
  }

  .custom-picker {
    width: 100%;
    background: #fff;
    position: absolute;
    bottom: -500rpx;
    border-radius: 16rpx 16rpx 0 0;

    &.hide-in {
      // transform: translate(0, -500rpx);
      bottom: 0rpx;
      transition: all 0.7s linear 0.4s;
    }
  }

  .custom-picker-header {
    width: 100%;
    padding-left: 32rpx;
    padding-right: 32rpx;
  }

  .custom-picker-body {
    width: 100%;
  }

  .custom-picker-item {
    position: relative;
    text-align: center;

    .bottom-line {
      content: '';
      height: 2rpx;
      width: 80%;
      position: absolute;
      left: 10%;
      background: rgba(0, 0, 0, .16);
      margin-top: 10rpx;
    }
  }
}

.detail-box {
  padding: 16px 0;
}

.wuliu-input {
  .scan-icon {
    display: float;
    position: absolute;
    right: 10rpx;
    top: 14rpx;
    z-index: 10000;
  }

}

.item-border {
  padding: 32rpx 0;
  border-bottom: 1px solid #E0E3E1;
}

.btn-box {
  width: 248rpx;
  border-radius: 16rpx;
}
</style>
